<template>
  <scroll-view scroll-y="ture" style="height: 100vh" class="share_content">
    <view v-if="isError" class="content">
      <image class="error_image" :src="oss2('funCard/error_icon.png')" />
      <view class="error_text">链接已失效或奖品已被领取</view>
      <view class="ok_btn" @click.stop="toHome">返回礼品卡</view>
    </view>

    <view v-else>
      <view v-if="!beShared" class="content">
        <view class="share_title">您的心意正等待送出</view>
        <image class="card_image" :src="orderInfo.giftCardFront" />

        <view class="show_title">
          {{ orderInfo.giftCardWord }}
          <image class="line_1" :src="oss2('funCard/card_line.png')" />
          <image class="line_2" :src="oss2('funCard/card_line.png')" />
        </view>

        <view class="show_user">
          From:<image :src="userImage" />
          <span class="user_name">{{
            orderInfo.memberName || "微信用户"
          }}</span>
        </view>
        <view class="goods_name">奥利奥乳酪蛋糕</view>
        <image class="goods_image" :src="goodsImage" />
        <view class="goods_sku">
          <view class="sku">{{ skuInfo }}</view>
          <view class="quantity">{{ skuQuantity }}份</view>
        </view>
        <label class="notice">
          *本次“玩心FUN享卡”仅在付款完成后24小时内有效，请及时分享好友填写收货地址，切勿随意分享给多人。
        </label>

        <button open-type="share" class="send_btn" @click="toShare">
          <label>分享好友 填写地址</label>
          <image :src="oss2('funCard/share_icon.png')" />
        </button>
      </view>

      <view v-else class="content">
        <view class="shared_title">
          <view class="shared_user">
            <image :src="userImage" />
            <span class="user_name">{{
              orderInfo.memberName || "微信用户"
            }}</span>
          </view>
          <view class="show_title">
            {{ orderInfo.giftCardWord }}
            <image class="line_1" :src="oss2('funCard/card_line.png')" />
            <image class="line_2" :src="oss2('funCard/card_line.png')" />
          </view>
          <image class="card_image" :src="orderInfo.giftCardFront" />
        </view>

        <view class="share_title">- 你的礼物 -</view>
        <view class="share_text">奥利奥乳酪蛋糕</view>
        <image class="goods_image" :src="goodsImage" />
        <view class="goods_sku">
          <view class="sku">{{ skuInfo }}</view>
          <view class="quantity">{{ skuQuantity }}份</view>
        </view>
        <view
          class="address_btn"
          @click.stop="toAddress('/funCard/address?orderId=' + orderId, true)"
          :style="{
            backgroundImage: `url(${oss2('funCard/but_shouhuo.png')})`,
          }"
        >
        </view>
      </view>
    </view>
  </scroll-view>


</template>

<script setup>
import {
  onLoad,
  onShow,
  onUnload,
  onHide,
  onShareAppMessage,
} from "@dcloudio/uni-app";
import { ref } from "vue";
import { oss2, message } from "@/utils/utils";
import { userLogin } from "@/services/utils";
import { GetOrderInfo } from "@/services/giftcard.js";
import privacyPopup from "@/components/privacy-popup";

let enterTime = "";
let outTime = "";
let stayTime = "";

const orderId = ref(0);
const userImage = ref("");
const orderInfo = ref("");
const goodsImage = ref("");
const skuInfo = ref("");
const skuQuantity = ref(0);

const beShared = ref(true);
const isError = ref(false);

onLoad((option) => {
  if (!uni.getStorageSync("TOKEN")) {
    uni.login({
      provider: "weixin",
      success: async (res) => {
        const loginParam = {
          type: 1,
        };
        loginParam.code = res.code;

        const { data } = await userLogin(loginParam);
        uni.setStorageSync("OPENID", data?.openId);
        uni.setStorageSync("UNIONID", data?.unionId);
        uni.setStorageSync("TOKEN", data?.accessToken);
        getApp().emdlz2("set", "user", "openid", data.openId);
        getApp().emdlz2("set", "user", "unionId", data.unionId);

        if (option.orderId) {
          uni.setStorageSync("SHAREID", option.orderId);
          getOrderInfo(option.orderId);
        } else {
          const shareId = uni.getStorageSync("SHAREID");
          getOrderInfo(shareId);
        }
      },
    });
  } else {
    if (option.orderId) {
      uni.setStorageSync("SHAREID", option.orderId);
      getOrderInfo(option.orderId);
    } else {
      const shareId = uni.getStorageSync("SHAREID");
      getOrderInfo(shareId);
    }
  }

  if (option.type) {
    beShared.value = false;
  }
  uni.hideShareMenu();
});
onShow(() => {
  // 用户进入时间
  enterTime = new Date();
  getApp().accessLogAdd();
});
onHide(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime?.getTime() - enterTime?.getTime()) / 1000;
  getApp().emdlz2(
    "track",
    "event",
    isError.value
      ? "fc_link_fail"
      : beShared.value
      ? "fc_receive_gift"
      : "fc_gift_giving",
    "view",
    isError.value
      ? "fc_link_page"
      : beShared.value
      ? "fc_receive_page"
      : "fc_gift_page",
    stayTime
  );
});
onUnload(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime?.getTime() - enterTime?.getTime()) / 1000;
  getApp().emdlz2(
    "track",
    "event",
    isError.value
      ? "fc_link_fail"
      : beShared.value
      ? "fc_receive_gift"
      : "fc_gift_giving",
    "view",
    isError.value
      ? "fc_link_page"
      : beShared.value
      ? "fc_receive_page"
      : "fc_gift_page",
    stayTime
  );
});

const getOrderInfo = async (id) => {
  console.log("id~", id);
  const res = await GetOrderInfo(id);
  if (res?.code === 200) {
    orderId.value = res.data.id;
    userImage.value = res.data.memberAvatar;
    if (res.data.orderStatus === 7) {
      orderInfo.value = res.data;
      goodsImage.value = res.data.items[0].productImageUrl;
      skuInfo.value = res.data.items[0].productSkuSpData[0].value;
      skuQuantity.value = res.data.items[0].productSkuQuantity;
    } else {
      isError.value = true;
    }
  } else {
    message(res.message);
  }
};
// const toReceive = () => {
//   getApp().emdlz2(
//     "track",
//     "event",
//     "fc_receive_gift",
//     "click",
//     "fc_happy_receive",
//     ""
//   );
// };
const toShare = () => {
  getApp().emdlz2("track", "event", "fc_gift_giving", "click", "fc_share", "");
};
onShareAppMessage((e) => {
  const pageUrl = "/funCard/share?orderId=" + uni.getStorageSync("SHAREID");

  const shareObj = {
    title: "送你一份奥利奥玩心小礼物，快来领取！", // 默认是小程序的名称(可以写slogan等)
    path: pageUrl, // 默认是当前页面，必须是以‘/’开头的完整路径
    imageUrl: oss2("funCard/gift_wx.png"), //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
    success: (res) => {
      if (res.errMsg == "shareAppMessage:ok") {
      }
    },
    fail: (err) => {
      console.log("转发失败之后的回调", err);
      if (res.errMsg == "shareAppMessage:fail cancel") {
        // 用户取消转发
        console.log("用户取消转发");
      } else if (res.errMsg == "shareAppMessage:fail") {
        // 转发失败，其中 detail message 为详细失败信息
        console.log("转发失败，其中detail message 为详细失败信息");
      }
    },
    complete: () => {
      // 转发结束之后的回调（转发成不成功都会执行）
      console.log("转发结束之后的回调（转发成不成功都会执行）");
    },
  };
  getApp().emdlz2("track", "event", "fc_gift_giving", "click", "fc_share", "");
  return shareObj;
});

const toAddress = (path, redirect) => {
  getApp().emdlz2("track", "event", "fc_gift_detail", "click", "fc_address", "");
  if (
    getApp().globalData.user.nickname === null ||
    getApp().globalData.user.nickname === "" ||
    getApp().globalData.user.nickname === undefined
  ) {
    console.log(123456);
    return getApp().getWechatUserProfile({ path, redirect });
  }
  if (
    getApp().globalData.user.phone === null ||
    getApp().globalData.user.phone === ""
  ) {
    uni.setStorageSync("REDIRECT_URI", JSON.stringify({ path, redirect }));
    uni.navigateTo({ url: "/pages/vip/register" });
    return;
  }
  if (redirect) return uni.redirectTo({ url: path });
  uni.redirectTo({ url: path });
  // uni.redirectTo({
  //   url: "/funCard/address?orderId=" + orderId.value,
  // });
};
const toHome = () => {
  getApp().emdlz2("track", "event", "fc_link_fail", "click", "fc_back_card", "");
  uni.redirectTo({
    url: "/funCard/index",
  });
};
</script>

<style lang="less" scoped>
@import "@/static/css/theme.less";
@keyframes PopupAm {
  from {
    transform: translateY(50px);
    opacity: 0;
  }

  to {
    transform: translateY(0);
    opacity: 1;
  }
}
.share_content {
  width: 375px;
  background-color: #fff;
  text-align: center;
  font-family: Source Han Sans CN;
  font-weight: 500;
  color: #000000;
  .content {
    min-height: 100vh;
    box-sizing: border-box;
    padding: 25px 0;
    animation: PopupAm 0.5s;
    -moz-animation: PopupAm 0.5s; /* Firefox */
    -webkit-animation: PopupAm 0.5s; /* Safari 和 Chrome */
    -o-animation: PopupAm 0.5s; /* Opera */
  }
  .error_image {
    width: 80px;
    height: 80px;
    margin-bottom: 21px;
    margin-top: calc((50vh - 180px));
  }
  .error_text {
    height: 12px;
    line-height: 12px;
    font-size: 12px;
    font-weight: 400;
    color: #747474;
  }
  .share_title {
    height: 20px;
    line-height: 20px;
    font-size: 20px;
    font-weight: bold;
  }
  .card_image {
    width: 235px;
    height: 144px;
    border-radius: 8px;
    margin-top: 17px;
  }
  .show_title {
    position: relative;
    width: 236px;
    height: 62px;
    line-height: 36px;
    font-size: 15px;
    color: #000000;
    margin: 0 auto;
    image {
      position: absolute;
      left: 0;
      width: 236px;
      height: 1px;
    }
    .line_1 {
      top: 31px;
    }
    .line_2 {
      bottom: 0;
    }
  }
  .show_user {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    width: 222px;
    height: 36px;
    margin: 12px auto;
    font-size: 15px;
    color: #000000;
    image {
      width: 36px;
      height: 36px;
      border-radius: 50%;
      margin-left: 6px;
      margin-right: 4px;
    }
    .user_name {
      font-size: 10px;
      font-weight: 400;
      color: #6f6f6f;
    }
  }
  .goods_image {
    width: 141px;
    height: 141px;
    border-radius: 5px;
    margin-top: 15px;
    margin-bottom: 15.5px;
  }

  .goods_name {
    font-size: 12px;
    color: #0044c9;
  }
  .goods_sku {
    height: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    margin-bottom: 53px;
    .name {
      padding-right: 12px;
      border-right: 2px solid #376799;
    }
    .sku {
      padding: 0 12px;
      border-right: 2px solid #376799;
    }
    .quantity {
      padding-left: 12px;
    }
  }
  .notice {
    display: block;
    text-align: center;
    padding: 0 12px;
    height: 30px;
    line-height: 15px;
    font-size: 10px;
    font-weight: 400;
    color: #ff0000;
  }
  .send_btn {
    margin: 0 auto;
    margin-top: 30px;
    width: 246px;
    height: 64px;
    background: #0044c9;
    box-shadow: 0px 4px 9px 0px rgba(0, 79, 234, 0.4);
    border-radius: 32px;
    font-size: 15px;
    font-weight: 400;
    color: #ffffff;
    display: flex;
    align-items: center;
    justify-content: center;
    label {
      display: block;
      width: 60px;
      height: 36px;
      line-height: 18px;
      margin-right: 24px;
    }
    image {
      width: 20px;
      height: 20px;
    }
  }
  .address_btn {
    width: 262px;
    height: 58px;
    margin: 0 auto;
    background-repeat: no-repeat;
    background-position: center center;
    background-size: 100% 100%;
  }
  .shared_title {
    position: relative;
    width: 336px;
    height: 301px;
    box-sizing: border-box;
    border-bottom: 1px solid #000;
    margin: 0 auto;
    margin-bottom: 18px;
    .shared_user {
      position: relative;
      width: 100%;
      height: 50px;
      line-height: 50px;
      font-size: 16px;
      font-weight: bold;
      color: #121212;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      image {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        margin-right: 15px;
      }
    }
  }
  .share_text {
    font-size: 12px;
    font-family: Source Han Sans CN;
    font-weight: 400;
    color: #0044c9;
    margin-top: 6px;
  }
  .ok_btn {
    position: absolute;
    left: 65px;
    bottom: calc(50vh - 240px);
    width: 246px;
    height: 42px;
    text-align: center;
    line-height: 42px;
    background: #0044c9;
    box-shadow: 0px 4px 9px 0px rgba(0, 79, 234, 0.4);
    border-radius: 21px;
    font-size: 15px;
    font-weight: 400;
    color: #ffffff;
  }
}
</style>
